package concurrent;

import java.util.concurrent.TimeUnit;

/**
 * TODO 简单说明
 *
 * @author yangyang
 * @date 2017/7/5 9:23
 * @email kekecany@163.com
 */

class NeedsCleanUp {
    private int id;

    NeedsCleanUp(int id) {
        this.id = id;
        System.out.println("needs clean up: " + id);
    }

    void cleanUp() {
        System.out.println("clean up: " + id);
    }
}

class Blocked3 implements Runnable {

    private volatile double d = 1.0;

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                NeedsCleanUp cleanUp1 = new NeedsCleanUp(1);
                try {
                    System.out.println("sleeping 1 second");
                    TimeUnit.SECONDS.sleep(1);
                    NeedsCleanUp cleanUp2 = new NeedsCleanUp(2);
                    try {
                        System.out.println("complex operation");
                        for (int i = 0; i < 2500000; i++) {
                            d = d + Math.PI * d;
                        }
                        System.out.println("finished complex operation");
                    } finally {
                        cleanUp2.cleanUp();
                    }
                }
               /* catch (InterruptedException e) {
                    System.out.println("----------------- exit from interruption ---------------");
                }*/
                finally {
                    System.out.println("********Thread.currentThread().isInterrupted()*********" + Thread.currentThread().isInterrupted());
                    cleanUp1.cleanUp();
                }
            }
        }catch (InterruptedException e) {
            System.out.println("exit from interruption");
        }finally {
            System.out.println("exit");
        }
    }
}

public class InterruptingIdiom {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Blocked3());
        thread.start();
        TimeUnit.MILLISECONDS.sleep(10);
        thread.interrupt();
    }
}
